/**
 * Copyright (c) 2018 苍穹跃龙
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.l.configuration;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.l.core.freemarker.DictItemModel;
import com.l.core.freemarker.JsonModel;
import com.l.core.freemarker.SystemConfigModel;
import com.l.core.freemarker.UserMenuTreeModel;

/**
 * @author 严秋旺
 * @date 2018-09-19
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.l.core",
        "com.l.web" }, includeFilters = @ComponentScan.Filter(classes = Controller.class), useDefaultFilters = false)
public class ServletConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private ServletContext servletContext;
    @Autowired
    private JsonModel jsonModel;
    @Autowired
    private UserMenuTreeModel userMenuTreeModel;
    @Autowired
    private DictItemModel dictItemModel;
    @Autowired
    private SystemConfigModel systemConfigModel;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(
                Charset.forName("utf-8"));
        converters.add(stringHttpMessageConverter);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(
                objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("utf-8");
        multipartResolver.setMaxUploadSize(20971520);// 20M=1024*1024*20
        multipartResolver.setMaxInMemorySize(3145728);
        return multipartResolver;
    }

    private Properties freemarkerSettings() {
        Properties setting = new Properties();
        setting.setProperty("tag_syntax", "auto_detect");
        setting.setProperty("classic_compatible", "true");
        setting.setProperty("whitespace_stripping", "true");
        setting.setProperty("template_update_delay", "0");
        setting.setProperty("locale", "zh_CN");
        setting.setProperty("localized_lookup", "false");
        setting.setProperty("default_encoding", "UTF-8");
        setting.setProperty("url_escaping_charset", "UTF-8");
        setting.setProperty("datetime_format", "yyyy-MM-dd HH:mm:ss");
        setting.setProperty("date_format", "yyyy-MM-dd");
        setting.setProperty("time_format", "HH:mm:ss");
        setting.setProperty("number_format", "#0.##########");
        setting.setProperty("template_exception_handler", "ignore");
        setting.setProperty("auto_include", "/include.ftl");
        setting.setProperty("auto_import", "/common.ftl as com");
        return setting;
    }

    private Map<String, Object> freemarkerVariables() {
        Map<String, Object> variables = new HashMap<>();
        variables.put("base", servletContext.getContextPath());
        variables.put("json", jsonModel);
        variables.put("userMenuTree", userMenuTreeModel);
        variables.put("dictItem", dictItemModel);
        variables.put("systemConfig", systemConfigModel);
        return variables;
    }

    @Bean
    public FreeMarkerConfig freemarkerConfig() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("/WEB-INF/ftl");
        configurer.setDefaultEncoding("utf-8");
        configurer.setFreemarkerSettings(freemarkerSettings());
        configurer.setFreemarkerVariables(freemarkerVariables());
        return configurer;
    }

    @Bean
    public FreeMarkerViewResolver freeMarkerViewResolver() {
        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setContentType("text/html; charset=UTF-8");
        resolver.setExposeRequestAttributes(true);
        resolver.setExposeSessionAttributes(true);
        resolver.setCache(true);
        resolver.setSuffix(".ftl");
        resolver.setOrder(0);
//		resolver.setAttributesMap(attributes);

        return resolver;
    }

    // 配置静态资源的处理,对静态资源的请求转发到servlet容器中默认的servlet上(对静态资源的请求不做处理)
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/res/**").addResourceLocations("/res/");
    }

}
